from google.appengine.ext import db
from google.appengine.api import memcache
import logging
import password

class WPConfig(db.Model):
    cfgCacheTime = db.IntegerProperty(required=True)
    cacheTime = db.IntegerProperty(required=True)
    maxSize = db.IntegerProperty(required=True)
    siteKey = db.StringProperty()
    cryptoMode = db.StringProperty()

def getConfig():
    config = memcache.get('config', namespace='wp_config')
    if config is None:
        cfg = WPConfig.all().get()
        if not cfg:#No Entry
            cfg = WPConfig(cfgCacheTime = password.cfgCacheTime,
                           cacheTime = password.cacheTime,
                           maxSize = password.maxSize,
                           siteKey = password.siteKey,
                           cryptoMode = password.cryptoMode);
            cfg.put()
        config = {'cacheTime':cfg.cacheTime, 'maxSize':cfg.maxSize,
                  'siteKey':cfg.siteKey.encode('utf-8').decode('string_escape'),
                  'crypto':cfg.cryptoMode.encode('utf-8')}
        if not memcache.set('config', config, cfg.cfgCacheTime, namespace='wp_config'):
            logging.error('Memcache set wp_config failed')
    return config

def init_config(crypto_cls):
    config = getConfig()
    config['crypto'] = crypto_cls(config['crypto'])
    return config
